package com.otitan.la.forest.industry.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.auth.framework.basepro.common.AuthCommon;
import com.otitan.la.forest.industry.client.http.HttpGet;
import com.otitan.la.forest.industry.constant.DicEnum;
import com.otitan.la.forest.industry.constant.DicTypeEnum;
import com.otitan.la.forest.industry.constant.OutputStatusEnum;
import com.otitan.la.forest.industry.constant.DicTypeEnum;
import com.otitan.la.forest.industry.constant.OutputStatusEnum;
import com.otitan.la.forest.industry.constant.StaticConstant;
import com.otitan.la.forest.industry.dto.OutputStatisticalDTO;
import com.otitan.la.forest.industry.dto.ProductStatisticalDTO;
import com.otitan.la.forest.industry.entity.AuditRecordsEntity;
import com.otitan.la.forest.industry.entity.OutputStatisticalEntity;
import com.otitan.la.forest.industry.mapper.OutputStatisticalMapper;
import com.otitan.la.forest.industry.service.AuditRecordsService;
import com.otitan.la.forest.industry.service.OutputStatisticalService;
import com.otitan.la.forest.industry.utils.DateUtil;
import com.otitan.la.forest.industry.entity.OutputStatisticalEntity;
import com.otitan.la.forest.industry.dto.OutputStatisticalDTO;
import com.otitan.la.forest.industry.utils.CommonUtils;
import com.otitan.la.forest.industry.utils.HttpResultUtil;
import com.otitan.la.forest.industry.utils.ImOrExportUtil;
import com.otitan.la.forest.industry.vo.*;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

import static com.otitan.la.forest.industry.constant.FilePathConstant.FINDCODEANDID_BY_ORG;
import static com.otitan.la.forest.industry.constant.FilePathConstant.FINDCODE_BY_PARENT;
import static com.otitan.la.forest.industry.constant.FilePathConstant.FINDORG_BY_ID;
import static com.otitan.la.forest.industry.constant.OutputStatusEnum.NOT_REPORT;

@Slf4j
@Service
public class OutputStatisticalServiceImpl extends ServiceImpl<OutputStatisticalMapper, OutputStatisticalEntity> implements OutputStatisticalService {

    @Value("${sysServer.path}")
    String sysServerPath;

    @Value("${la-forest-industry.file.excel-folder}")
    private String excelFolder;

    @Value("${redis.key-prefix}")
    private String redisKeyPrefix;

    @Autowired
    private AuthCommon authCommon;
    @Autowired
    private AuditRecordsService auditRecordsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OutputStatisticalMapper outputStatisticalMapper;

    @Override
    @Transactional
    public DataResult add(OutputStatisticalEntity outputStatistical, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }

        outputStatistical.setId(CommonUtils.getUUID());

        JSONObject loginOrgInfo = CommonUtils.getUserOrgInfo(authCommon);
        JSONObject userInfo = authCommon.getLoginUserInfo();
        if (CollUtil.isNotEmpty(loginOrgInfo)){
            outputStatistical.setAreaCode(loginOrgInfo.get("areaCode").toString());
            outputStatistical.setUnitId(loginOrgInfo.get("id").toString());
            outputStatistical.setStatus(OutputStatusEnum.NOT_REPORT.getValue());
            outputStatistical.setInputUser(userInfo.get("realName").toString());
        }

        LambdaQueryWrapper<OutputStatisticalEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OutputStatisticalEntity::getYear, outputStatistical.getYear());
        queryWrapper.eq(OutputStatisticalEntity::getUnitId, outputStatistical.getUnitId());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("该单位已填写产业产值信息");
        }

        // 添加审核记录
        AuditRecordsEntity auditRecordsEntity = new AuditRecordsEntity();
        auditRecordsEntity.setDataId(outputStatistical.getId());
        auditRecordsEntity.setStatus(OutputStatusEnum.NOT_REPORT.getValue());
        auditRecordsEntity.setOpinion("数据新增");
        auditRecordsService.save(auditRecordsEntity);

        boolean isSuccess = this.save(outputStatistical);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除林业产业产值统计表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success();
    }

    @Override
    public DataResult editor(OutputStatisticalEntity outputStatistical, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        LambdaQueryWrapper<OutputStatisticalEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.ne(OutputStatisticalEntity::getId, outputStatistical.getId());
        queryWrapper.eq(OutputStatisticalEntity::getYear, outputStatistical.getYear());
        queryWrapper.eq(OutputStatisticalEntity::getAreaCode, outputStatistical.getAreaCode());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("数据重复");
        }

        // 添加审核记录
        AuditRecordsEntity auditRecordsEntity = new AuditRecordsEntity();
        auditRecordsEntity.setDataId(outputStatistical.getId());
        if (OutputStatusEnum.NOT_REPORT.getValue().equalsIgnoreCase(outputStatistical.getStatus())){
            // 修改保存操作
            auditRecordsEntity.setOpinion("数据修改");
        } else {
            // 修改提交操作
            auditRecordsEntity.setOpinion("数据提交审核");
        }
        auditRecordsEntity.setStatus(OutputStatusEnum.NOT_REPORT.getValue());
        auditRecordsService.save(auditRecordsEntity);
        boolean isSuccess = this.updateById(outputStatistical);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
    }

    @Override
    public DataResult findPageData(long page, long size, OutputStatisticalDTO outputStatistical) {
        Page pagePlug = new Page(page, size);
        LambdaQueryWrapper<OutputStatisticalEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        //queryWrapper.eq(OutputStatisticalEntity::getId, outputStatistical.getId());
        if (StrUtil.isNotEmpty(outputStatistical.getYear())){
            queryWrapper.eq(OutputStatisticalEntity::getYear, outputStatistical.getYear());
        }
        if (StrUtil.isNotEmpty(outputStatistical.getAreaCode())){
            queryWrapper.eq(OutputStatisticalEntity::getAreaCode, outputStatistical.getAreaCode());
        }
        if (StrUtil.isNotEmpty(outputStatistical.getStatus())){
            queryWrapper.eq(OutputStatisticalEntity::getStatus, outputStatistical.getStatus());
        }

        // 查询用户组织机构 数据权限
        JSONObject userOrgInfo = CommonUtils.getUserOrgInfo(authCommon);
        if (CollUtil.isNotEmpty(userOrgInfo)){


        }

        IPage<OutputStatisticalEntity> iPage = this.page(pagePlug, queryWrapper);

        IPage<OutputStatisticalVO> iPageVO = new Page<>();
        BeanUtils.copyProperties(iPage, iPageVO);

        List<OutputStatisticalVO> listVO = new ArrayList<>();
        // 转换使用字典的属性
        if (CollUtil.isNotEmpty(iPage.getRecords())) {
            iPage.getRecords().forEach(item -> {
                OutputStatisticalVO vo = new OutputStatisticalVO();
                BeanUtils.copyProperties(item, vo);
                // 需要转换的具体字典属性
                String areaName = CommonUtils.getDicName(redisTemplate, redisKeyPrefix,
                        DicTypeEnum.AREA.getValue(), item.getAreaCode());
                vo.setAreaName(areaName);
                listVO.add(vo);
            });
        }
        iPageVO.setRecords(listVO);

        return DataResult.success(iPageVO);
    }

    @Override
    public DataResult findOne(String id) {
        OutputStatisticalEntity entity = this.getById(id);
        OutputStatisticalVO vo = new OutputStatisticalVO();
        BeanUtils.copyProperties(entity, vo);
        // 需要转换的具体字典属性

        return DataResult.success(vo);
    }

    @Override
    @Transactional
    public DataResult check(AuditRecordsEntity entity, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        String dataId = entity.getDataId();
        OutputStatisticalEntity data = getById(dataId);
        data.setStatus(entity.getStatus());
        this.updateById(data);
        boolean isSuccess = auditRecordsService.save(entity);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.OPERATION_ERRO.getMsg());
    }

    @Override
    public void exportZip(OutputStatisticalDTO outputStatisticalDTO, HttpServletResponse httpServletResponse) {

        LambdaQueryWrapper<OutputStatisticalEntity> queryWrapper = Wrappers.lambdaQuery();

//        Map<String, String> codeMap = new HashMap<>();
        Map<String, String> areaMap = ImOrExportUtil.getDicName(DicTypeEnum.AREA.getValue(), redisTemplate, redisKeyPrefix);


        if (CollUtil.isNotEmpty(outputStatisticalDTO.getIds())) {
            queryWrapper.in(OutputStatisticalEntity::getId, outputStatisticalDTO.getIds());
        } else {
            //年度
            if (StrUtil.isNotEmpty(outputStatisticalDTO.getYear())) {
                queryWrapper.eq(OutputStatisticalEntity::getYear, outputStatisticalDTO.getYear());
            } else {
                throw new RuntimeException("年度为必填项，请选择");
            }

            //状态
            if (StrUtil.isNotEmpty(outputStatisticalDTO.getStatus())) {
                queryWrapper.eq(OutputStatisticalEntity::getStatus, outputStatisticalDTO.getStatus());
            }

            //所属地区
            if (StrUtil.isNotEmpty(outputStatisticalDTO.getAreaCode())) {
                String path = sysServerPath + FINDCODE_BY_PARENT;
                Map<String, Object> map = new HashMap<>();
                map.put("parentCode", outputStatisticalDTO.getAreaCode());
                HttpGet httpGet = new HttpGet(path, authCommon.getTokenId(), map);
                httpGet.execute();
                String jsonStr = httpGet.readStr();

                if (StrUtil.isEmpty(jsonStr)) {
                    jsonStr = null;
                }

                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                int code = Integer.parseInt(jsonObject.getString("code"));
                if (code == 0) {
                    String data = jsonObject.getString("data");
                    Map<String, Object> codeToMap = JSON.parseObject(data, Map.class);
                    List<String> codeList = (List<String>) codeToMap.get("codeList");

                    if (CollUtil.isNotEmpty(codeList)) {
                        queryWrapper.in(OutputStatisticalEntity::getAreaCode, codeList);
                    }
//                    codeMap = (Map<String, String>) codeToMap.get("codeMap");
                }
                httpGet.releaseConnection();
            } else {
                throw new RuntimeException("所属地区为必填项，请选择");
            }

        }


        List<OutputStatisticalEntity> list = this.list(queryWrapper);

        List<OutputStatisticalVO> dtoList = new ArrayList<>();


        for (OutputStatisticalEntity entity : list) {
            OutputStatisticalVO dto = new OutputStatisticalVO();
            BeanUtils.copyProperties(entity, dto);
            String areaName = areaMap.get(entity.getAreaCode());
            dto.setAreaName(areaName);
            String yearName = entity.getYear() + "年";
            dto.setYearName(yearName);
            if (entity.getSubmitDate() != null) {
                String submitDateName = DateUtil.dateToString(entity.getSubmitDate(), DateUtil.YYYY_MM_DD);
                dto.setSubmitDateName(submitDateName);
            }

            if(StrUtil.isNotEmpty(entity.getUnitId())){
                String path = sysServerPath + FINDORG_BY_ID;
                Map<String, Object> parameMap = new HashMap<>();
                parameMap.put("id", entity.getUnitId());
                HttpGet httpGet = new HttpGet(path, authCommon.getTokenId(), parameMap);
                httpGet.execute();
                String jsonStr = httpGet.readStr();

                if (StrUtil.isEmpty(jsonStr)) {
                    jsonStr = null;
                }

                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                int code = Integer.parseInt(jsonObject.getString("code"));
                if (code == 0) {
                    String data = jsonObject.getString("data");
                    Map<String, Object> codeToMap = JSON.parseObject(data, Map.class);
                    String name = (String) codeToMap.get("name");
                    dto.setOrgName(name);
                }
                httpGet.releaseConnection();
            }

            dtoList.add(dto);
        }

        Map<String, List<OutputStatisticalVO>> collect = dtoList.stream()
                .collect(Collectors.groupingBy(item -> {
                    if (StrUtil.isEmpty(item.getAreaName())) {
                        return "";
                    }
                    return item.getAreaName();
                }));

        List<String> filePaths = new ArrayList<>();
        // 按照村保存Excel文件
        for (List<OutputStatisticalVO> value : collect.values()) {
            String filePath = ImOrExportUtil.saveExcelFile(excelFolder, value);
            if (StrUtil.isNotEmpty(filePath)) {
                filePaths.add(filePath);
            }
        }
        // 创建压缩文件，并下载
        ImOrExportUtil.mackZipAndDownload(httpServletResponse, filePaths, outputStatisticalDTO.getYear());


    }

    @Override
    public DataResult statistical(ProductStatisticalDTO productStatisticalDTO) {
           /* Integer year = productStatisticalDTO.getYear();
        Integer month = productStatisticalDTO.getMonth();
        String startDate = DateUtil.getBeginTime(year, month);
        String endDate = DateUtil.getEndTime(year, month);*/
        Map<String, Object> map = new HashMap<>();
        String colum = "";
        Integer type = productStatisticalDTO.getType();
        switch (type) {
            case 0:
                colum = "TATAL_TATALVALUE";
                break;
            case 1:
                colum = "FIS_TATAL_TATALVALUE";
                break;
            case 2:
                colum = "SEC_TATAL_TATALVAL";
                break;
            case 3:
                colum = "THI_TATAL_TATALVALUE";
                break;
        }
        productStatisticalDTO.setColum(colum);
        //总产值在各地市分布情况

        List<Map<String, Object>> mapAddress = outputStatisticalMapper.findSizeByYear(productStatisticalDTO);
        map.put("mapAddress",mapAddress);
        Integer year = productStatisticalDTO.getYear();

        //最近5年
        List<Integer> yearList = Arrays.asList(year, year - 1, year - 2, year - 3, year - 4);
        String yearStr=year+","+(year - 1)+","+(year - 2)+","+(year - 3)+","+(year - 4);
        //最近5年的总产值走势
        List<FiveYearProductVO> mapFiveYear = outputStatisticalMapper.findSizeGroupByYear(productStatisticalDTO, yearList,yearStr);
        List<FiveYearProductVO> newMapFiveYear = new ArrayList<>();
        newMapFiveYear = mapFiveYear;
    /*    for (int years : yearList) {
            boolean istrue=false;
            for (FiveYearProductVO five : mapFiveYear) {
                //判断数据库里面有没有对应日期的值，没有的话补上
                if (five.getYear() == years) {
                    istrue=true;
                    break;
                }
            }
            //如果数据库里面有对应日期跳出循环
            if(istrue){
                continue;
            }
            FiveYearProductVO fiveYearProductVO = new FiveYearProductVO(years, "0");
            newMapFiveYear.add(fiveYearProductVO);
        }*/
        map.put("mapFiveYear", mapFiveYear);
        List<Map<String, Object>> mapFiveYearProduct = null;
        List mapFiveYearProductAccounted = new ArrayList();
        if (type == 0) {
            mapFiveYearProduct = outputStatisticalMapper.findAllThreeProductGroupByYear(productStatisticalDTO, yearList,yearStr);
            AllThreeProductAccountedVO all = outputStatisticalMapper.findallThreeProductAccounted(productStatisticalDTO, yearList);
            AllThreeProductAccountedVO allThreeProductAccounted = all.getAllThreeProductAccounted(all);
            mapFiveYearProductAccounted.add(allThreeProductAccounted);
        } else if (type == 1) {
            mapFiveYearProduct = outputStatisticalMapper.findFirstProductGroupByYear(productStatisticalDTO, yearList,yearStr);
            FirstProductAccountedVO first = outputStatisticalMapper.findFirstProductAccounted(productStatisticalDTO, yearList);
            FirstProductAccountedVO firstProductAccounted = first.getFirstProductAccounted(first);
            mapFiveYearProductAccounted.add(firstProductAccounted);
        } else if (type == 2) {
            mapFiveYearProduct = outputStatisticalMapper.findSecendProductGroupByYear(productStatisticalDTO, yearList,yearStr);
            SecendProductAccountedVO secend = outputStatisticalMapper.findSecendProductAccounted(productStatisticalDTO, yearList);
            SecendProductAccountedVO secendProductAccounted = secend.getSecendProductAccounted(secend);
            mapFiveYearProductAccounted.add(secendProductAccounted);
        } else if (type == 3) {
            mapFiveYearProduct = outputStatisticalMapper.findThreeProductGroupByYear(productStatisticalDTO, yearList,yearStr);
            ThreeProductAccountedVO three = outputStatisticalMapper.findThreeProductAccounted(productStatisticalDTO, yearList);
            ThreeProductAccountedVO threeProductAccounted = three.getThreeProductAccounted(three);
            mapFiveYearProductAccounted.add(threeProductAccounted);
        }
        map.put("mapFiveYearProductAccounted",mapFiveYearProductAccounted);
        map.put("mapFiveYearProduct",mapFiveYearProduct);
        return DataResult.success(map);
    }

    @Override
    public DataResult importFile(MultipartFile file) throws IOException {
        String fileOriginalFilename = file.getOriginalFilename();
        if (StrUtil.isNotEmpty(fileOriginalFilename)) {
            String suffix = fileOriginalFilename.substring(fileOriginalFilename.lastIndexOf(".") + 1);
            if (StaticConstant.FILE_EXTENSION_XLS.equalsIgnoreCase(suffix)) {

                Map<String, String> areaMap = ImOrExportUtil.getDicName(DicEnum.AREA.getValue(), redisTemplate, redisKeyPrefix);

                Workbook workbook = null;

                InputStream inputStream = file.getInputStream();
                workbook = new HSSFWorkbook(inputStream);

                Sheet sheet = workbook.getSheetAt(0);

                int firstRowNum = sheet.getFirstRowNum();
                int rowStart = firstRowNum + 1;
                int rowEnd = sheet.getLastRowNum();

                Map<String, Object> map = new HashMap<>();
                for (int rowNum = rowStart; rowNum <= rowEnd; rowNum++) {

                    Row row = sheet.getRow(rowNum);
                    if (null == row) {
                        continue;
                    }
                    if (rowNum <= 3) {
                        if (rowNum == 1) {
                            JSONArray loginOrgInfo = authCommon.getLoginOrgInfo();
                            String org = null;
                            if (CollUtil.isNotEmpty(loginOrgInfo)){
                                if (loginOrgInfo.size() > 0) {
                                    for (Object jsonObject : loginOrgInfo) {
                                        Map<String, String> userMap = (Map<String, String>) jsonObject;
                                        for (Map.Entry<String, String> entry : userMap.entrySet()) {
                                            if(entry.getKey().equals("name")){
                                                org = entry.getValue();
                                            }
                                        }
                                    }
                                }
                            }

                            String orgStr = ImOrExportUtil.getCellValue(row.getCell(0));
                            int index = orgStr.indexOf("：");
                            String orgName = orgStr.substring(index + 1).trim();

                            if(!org.equals(orgName)){
                                return DataResult.fail("您导入的组织机构名与当前用户的组织机构名不匹配,无权限导入");
                            }

                            if(orgName.contains("xxx")){
                                return DataResult.fail("excel表中的综合机关名称输入框未输入值");
                            }

                            String path = sysServerPath + FINDCODEANDID_BY_ORG;
                            Map<String, Object> parameMap = new HashMap<>();
                            parameMap.put("orgName", orgName);
                            HttpGet httpGet = new HttpGet(path, authCommon.getTokenId(), parameMap);
                            httpGet.execute();
                            String jsonStr = httpGet.readStr();

                            if (StrUtil.isEmpty(jsonStr)) {
                                jsonStr = null;
                            }

                            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                            int code = Integer.parseInt(jsonObject.getString("code"));
                            if (code == 0) {
                                String data = jsonObject.getString("data");
                                Map<String, Object> codeToMap = JSON.parseObject(data, Map.class);
                                String unitId = (String) codeToMap.get("id");
                                String areaCode = (String) codeToMap.get("areaCode");
                                map.put("unitId",unitId);
                                map.put("areaCode",areaCode);

                            }
                            httpGet.releaseConnection();

                            String yearAndRtimeinterStr = ImOrExportUtil.getCellValue(row.getCell(1)).trim();

                            if(yearAndRtimeinterStr.contains("xxxx")){
                                return DataResult.fail("excel表中的年份输入框框未输入值");
                            }

                            String year = yearAndRtimeinterStr.replace("年", "").trim();
//                            String yearAndRtimeinter = str.replace("月", "");
//                            String[] array = yearAndRtimeinter.split("-");
                            map.put("year", year);
//                            map.put("reportTimeinter", array[1]);
                        }
                    } else if (rowNum >= 4 && rowNum <= 57) {
                        String[] totalValueArray = ImOrExportUtil.totalValueArray();
                        String[] addValueArray = ImOrExportUtil.addValueArray();
                        map.put(totalValueArray[rowNum - 4], ImOrExportUtil.getCellValue(row.getCell(3)));
                        map.put(addValueArray[rowNum - 4], ImOrExportUtil.getCellValue(row.getCell(4)));
                    } else if (rowNum > 59) {
                        if (rowNum == 60) {
                            String unitDutyUser = ImOrExportUtil.getCellValue(row.getCell(0));
                            int index = unitDutyUser.indexOf("：");
                            String unitDutyUserStr = unitDutyUser.substring(index + 1).trim();
                            if(unitDutyUserStr.contains("xx")){
                                return DataResult.fail("excel表中的单位负责人输入框框未输入值");
                            }

                            JSONObject userInfo = authCommon.getLoginUserInfo();
                            String inputUser = userInfo.get("realName").toString();

                            String SubmitDateStr = ImOrExportUtil.getCellValue(row.getCell(4));
                            if(unitDutyUserStr.contains("xxxx-xx-xx")){
                                return DataResult.fail("excel表中的报出日期输入框框未输入值");
                            }

                            int submitIndex = SubmitDateStr.indexOf("：");
                            String submitDate = SubmitDateStr.substring(submitIndex + 1).trim();
                            Date date = DateUtil.cellStrToDate(submitDate);
                            map.put("submitDate", date);
                            map.put("unitDutyUser", unitDutyUserStr);
                            map.put("inputUser", inputUser);
                        }

                        if (rowNum == 61) {
                            String statisDutyUser = ImOrExportUtil.getCellValue(row.getCell(2));
                            map.put("statisDutyUser", statisDutyUser);
                        }
                    }
                }
                map.put("status", OutputStatusEnum.NOT_REPORT.getValue());
                OutputStatisticalEntity entity = JSONObject.parseObject(JSONObject.toJSONString(map), OutputStatisticalEntity.class);
                if (StrUtil.isNotEmpty(entity.getUnitId()) && StrUtil.isNotEmpty(entity.getYear())) {

                    LambdaQueryWrapper<OutputStatisticalEntity> queryWrapper = Wrappers.lambdaQuery();
                    queryWrapper.eq(OutputStatisticalEntity::getUnitId, entity.getUnitId());
                    queryWrapper.eq(OutputStatisticalEntity::getYear, entity.getYear());

                    Integer count = outputStatisticalMapper.selectCount(queryWrapper);
                    if (count > 0) {
                        return DataResult.fail("导入的综合机关名称和年份已经存在,请重新导入");
                    }
                }
                outputStatisticalMapper.insert(entity);
                return DataResult.success();
            } else {
                return DataResult.fail("不支持的文件格式");
            }
        }
        return DataResult.fail("文件名错误");
    }
}